//
//  CinemaTableViewController.m
//  ShowTimeApp
//
//  Created by Ruby on 10/21/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CinemaTableViewController.h"
#import "CustomCellOne.h"
#import "TabBarCinemaViewController.h"
#import "CinemaInfo.h"
#import "MovieInfo.h"
#import "MoviesByCinema.h"
#import "PriceInfo.h"
#import "CinemaInfoViewController.h"

#import "CinemaDataModel.h"
#import "MovieDataModel.h"
#import "ShowtimeDataModel.h"
#import "TicketInfoDataModel.h"

#import "CinemaService.h"
#import "ServiceAccessHelper.h"

#define PURPLE_COLOR	[UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f]
@implementation CinemaTableViewController
@synthesize dbcinemaList,svCinemaList,svShowTime,svMovieList,svTicketInfo,filteredCinemaArray;
@synthesize searchBar;
@synthesize searchDC;
@synthesize spinner;
@synthesize cinemaList;

NSString* const SERVICELINK=@"http://192.168.254.1/CinemaService.asmx";
NSString* const CINEMA=@"CINEMA";
NSString* const MOVIE=@"MOVIE";
NSString* const TICKETINFO=@"TICKETINFO";
NSString* const SHOWTIME=@"SHOWTIME";

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        [self initSpinner];
        [self initDataModel];
        [spinner startAnimating];
        //check if device can connect internet
        BOOL hasInternetConnection=NO;
        if(hasInternetConnection){
            //Remove all data in device's db: call delete all data here
            [ticketInfoDataModel deleteAll];
            [showtimeDataModel deleteAll];
            [cinemaDataModel deleteAll];
            [movieDataModel deleteAll];
            if([self saveChanges]==YES)
            {
                NSLog(@"Delete data successfully");
            }
            
            //Get all data async from service
            [self initServiceAccessHelper];//Initialize ServiceAccessHelper
            [self getCinemaListAsyncFromSV];//call async methods to get data from webservice
            
        }else{
            //Get cinema list from device's db
            [self getCinemaListFromDB];
            //For Testing: Show output data for testing, add objects, delete objects
            //            cinemaDataModel = [[CinemaDataModel alloc]initCinemaDataModel];
            //            [cinemaDataModel output:[cinemaDataModel getAllCinemaSortByNameAscending]];
            //            movieDataModel=[[MovieDataModel alloc]initMovieDataModel];
            //            [movieDataModel output:[movieDataModel getAllMovieSortByTitleAscending]];
            //            showtimeDataModel=[[ShowtimeDataModel alloc]initShowtimeDataModel];
            //            [showtimeDataModel output:[showtimeDataModel getAllShowtimeByCinemaSortByDateAscending:1 withMovieID:1]];
            //            ticketInfoDataModel=[[TicketInfoDataModel alloc]initTicketInfoDataModel];
            //            [ticketInfoDataModel output:[ticketInfoDataModel getAllTickeInfoOfCinemaSortByIDAscending:1]];
            //            [cinemaDataModel addObjects];
            //            [myDataContext deleteAll];
            //            NSArray* list = [[NSArray alloc]init];
            //            list= [myDataContext getAllCinemaByGroupNameSortByIDAscending:@"'GALAXY'"];
            //            Cinema* cinema = [myDataContext getDetailByID:2];
            //            NSLog(@"%@-%@",cinema.Name,cinema.Address);
            //            [myDataContext getDetail];
        }
    }
    return self;
}

//Initialize ServiceAccessHelper
-(void)initServiceAccessHelper{
    serviceAccess= [[ServiceAccessHelper alloc]initWithServiceLink:SERVICELINK];
    svCinemaList=[[NSMutableArray alloc]init];
    svMovieList=[[NSMutableArray alloc]init];
    svShowTime=[[NSMutableArray alloc]init];
    svTicketInfo=[[NSMutableArray alloc]init];
}

//Initialize DataModel instance for each of Table, get data from db
-(void)initDataModel{
    cinemaDataModel = [[CinemaDataModel alloc] initCinemaDataModel];
    movieDataModel=[[MovieDataModel alloc]initMovieDataModel];
    showtimeDataModel=[[ShowtimeDataModel alloc]initShowtimeDataModel];
    ticketInfoDataModel=[[TicketInfoDataModel alloc]initTicketInfoDataModel]; 
}

-(void)getCinemaListAsyncFromSV{
    tableName=CINEMA;
    CinemaService_GetAllCinemas *parms = [[CinemaService_GetAllCinemas alloc]init];
    [serviceAccess.binding GetAllCinemasAsyncUsingParameters:parms delegate:self];
}

-(void)getMovieListAsyncFromSV{
    tableName=MOVIE;
    CinemaService_GetAllMoviesInCurrentDayToNext7DaysOfShowTime *parms =[[CinemaService_GetAllMoviesInCurrentDayToNext7DaysOfShowTime alloc]init];
    [serviceAccess.binding GetAllMoviesInCurrentDayToNext7DaysOfShowTimeAsyncUsingParameters:parms delegate:self];
}

-(void)getTicketInfoListAsyncFromSV{
    tableName=TICKETINFO;
    CinemaService_GetAllTicketInfo *parms=[[CinemaService_GetAllTicketInfo alloc]init];
    [serviceAccess.binding GetAllTicketInfoAsyncUsingParameters:parms delegate:self];
}

-(void)getShowTimeListAsyncFromSV{
    tableName=SHOWTIME;
    CinemaService_GetAllShowTimeInCurrentDayToNext7Days *parms = [[CinemaService_GetAllShowTimeInCurrentDayToNext7Days alloc]init];
    [serviceAccess.binding GetAllShowTimeInCurrentDayToNext7DaysAsyncUsingParameters:parms delegate:self];
}

-(void)operation:(CinemaServiceSoapBindingOperation *)operation completedWithResponse:(CinemaServiceSoapBindingResponse *)response{
    [NSThread sleepForTimeInterval:0.5];
    for(id mine in response.bodyParts){
        if(tableName==CINEMA){
            CinemaService_ArrayOfCinemaEntity* cinemaList = [mine GetAllCinemasResult];
            svCinemaList= [cinemaList.CinemaEntity retain]; 
            [self getTicketInfoListAsyncFromSV];
        }else if(tableName==TICKETINFO){
            CinemaService_ArrayOfTicketInfoEntity* ticketInfoList =[mine GetAllTicketInfoResult];
            svTicketInfo = [ticketInfoList.TicketInfoEntity retain];
            [self getMovieListAsyncFromSV];
        }else if(tableName==MOVIE){
            CinemaService_ArrayOfMovieEntity* movieList = [mine GetAllMoviesInCurrentDayToNext7DaysOfShowTimeResult];
            svMovieList = [movieList.MovieEntity retain];
            [self getShowTimeListAsyncFromSV];
        }else{
            CinemaService_ArrayOfShowTimeEntity* showTimeList =[mine GetAllShowTimeInCurrentDayToNext7DaysResult];
            svShowTime=[showTimeList.ShowTimeEntity retain];
            //Save all data from service to device's db
            if([self saveAllDataToDeviceDB])
                NSLog(@"Save successfully");
            else
                NSLog(@"Save unsuccessfully");
        }
    }
    //Get cinema list from device's db
    [self getCinemaListFromDB];
}

-(BOOL)saveAllDataToDeviceDB{
    NSError *error1,*error2,*error3,*error4=nil;
    if(svCinemaList!=nil){
        NSLog(@"CinemaList.count= %d",svCinemaList.count);
    }
    
    [cinemaDataModel insertObjects:svCinemaList];
    [movieDataModel insertObjects:svMovieList];
    [showtimeDataModel insertObjects:svShowTime];
    [ticketInfoDataModel insertObjects:svTicketInfo];
    if([cinemaDataModel saveContent:error1]&&[movieDataModel saveContent:error2]&&[showtimeDataModel saveContent:error3]&&[ticketInfoDataModel saveContent:error4]){
        return YES;
    }
    else{
        NSLog(@"ERROR %@, %@", error1, [error1 userInfo]);
        return NO;
    }
}

-(BOOL)saveChanges{
    NSError *error1,*error2,*error3,*error4=nil;
    if([cinemaDataModel saveContent:error1]&&[movieDataModel saveContent:error2]&&[showtimeDataModel saveContent:error3]&&[ticketInfoDataModel saveContent:error4]){
        return YES;
    }
    else
    {
        NSLog(@"ERROR %@, %@", error1, [error1 userInfo]);
        return NO;
    }
}

-(void)getCinemaListFromDB{
    dbcinemaList = [cinemaDataModel getAllCinemaSortByNameAscending];
    //Transfer data into MutableDictionary list: set key & value for each item
    self.cinemaList = [NSMutableDictionary dictionary];
	for (Cinema *item in dbcinemaList) 
    {
        [self.cinemaList setObject:item forKey:item.Name]; 
    }
    [spinner stopAnimating];
}

-(void)initSpinner{
    spinner = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.frame = CGRectMake(0.0, 0.0, 100, 100);
    [self.view addSubview:spinner];
    spinner.center = self.view.center;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title=@"Cinema";
    // Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.tintColor = PURPLE_COLOR;
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	self.tableView.tableHeaderView = self.searchBar;
	
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    //return [[myDataContext.fetchResultController sections]count];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    // Normal table
	if (tableView == self.tableView) 
        return self.cinemaList.count;
	
    // Search table
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name contains[cd] %@", self.searchBar.text];
	self.filteredCinemaArray = (NSMutableArray*)[dbcinemaList filteredArrayUsingPredicate:predicate];
	return self.filteredCinemaArray.count;
    //return dbcinemaList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //Init table with customized cell
    CustomCellOne *cell = (CustomCellOne*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:
        //         CellIdentifier] autorelease];
        cell=[[[NSBundle mainBundle]loadNibNamed:@"CustomCellOne" owner:self options:nil]lastObject];
        cell.selectionStyle=UITableViewCellSelectionStyleGray;
        cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
        cell.editingAccessoryType= UITableViewCellAccessoryNone;
    }
    
    Cinema* selectedCinema;
    if(tableView==self.tableView)
    {
        NSString* keyName = [self.cinemaList.allKeys objectAtIndex:indexPath.row];
        selectedCinema = [self.cinemaList objectForKey:keyName];
    }else
    {
        selectedCinema =(Cinema*)[self.filteredCinemaArray objectAtIndex:indexPath.row];
    }
    
    //selectedCinema =(Cinema*)[keyCollection objectAtIndex:indexPath.row];
    cell.titleLabel.text=[selectedCinema Name];
    cell.addressLabel.text=[selectedCinema Address];
    
    //    NSManagedObject *managedObject  = [myDataContext.fetchResultController.fetchedObjects objectAtIndex:indexPath.row];
    //Test voi data la danh sach font chu trong may
    //        cell.titleLabel.text =[[UIFont familyNames] objectAtIndex:indexPath.row]; 
    //        cell.addressLabel.text=[[UIFont familyNames] objectAtIndex:indexPath.row];
    //Test data voi du lieu lay tu db
    //    NSString* s = [(NSManagedObject*)[myDataContext.fetchResultController.fetchedObjects objectAtIndex:indexPath.row] valueForKey:@"Name"];    
    //    cell.titleLabel.text = [managedObject valueForKey:@"Name"];
    //    cell.addressLabel.text = [managedObject valueForKey:@"Address"];
    
    return (UITableViewCell *) cell;
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    Cinema* selectedCinema =[dbcinemaList objectAtIndex:indexPath.row];
    CinemaInfo* cinemaInfo = [[CinemaInfo alloc]initWithSelectedCinema:selectedCinema];
    //    CinemaInfoViewController *cinemaInfo = [[CinemaInfoViewController alloc]initWithSelectedCinema:selectedCinema];
    cinemaInfo.tabBarItem=[[UITabBarItem alloc]initWithTitle:@"Cinema Info" image:[UIImage imageNamed:@"cineInfo.png"] tag:0];
    MoviesByCinema* movieList = [[MoviesByCinema alloc] initWithSelectedCinema:selectedCinema];
    movieList.tabBarItem=[[UITabBarItem alloc]initWithTitle:@"Comming Movies" image:[UIImage imageNamed:@"movieList.png"] tag:0];
    movieList.tableView.backgroundColor=[UIColor colorWithRed:0.20392f green:0.19607f blue:0.61176f alpha:1.0f];
    PriceInfo* priceInfo=[[PriceInfo alloc]init];
    priceInfo.tabBarItem=[[UITabBarItem alloc]initWithTitle:@"Price Info" image:[UIImage imageNamed:@"ticketInfo.png"] tag:0];
    
    NSMutableArray* controllers = [NSMutableArray array];
    [controllers addObject:cinemaInfo];
    [controllers addObject:movieList];
    [controllers addObject:priceInfo];
    TabBarCinemaViewController* tabbar =[[TabBarCinemaViewController alloc]initWithControllers:controllers withTitle:selectedCinema.Name];
    [self.navigationController pushViewController:tabbar animated:YES];
}

//Return the height of cell
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 72;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	[self.searchBar setText:@""]; 
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}

@end
